<?php
class captcha{
	private $aes='';
	private $numChars=4;
	private $w;
	private $h = 20;
	private $colBG="188 220 231";
	private $colTxt="0 0 0";
	private $colBorder="0 128 192";
	private $charx=10;
	private $numCirculos=5;
	public function init($params=array()){
		foreach($params as $key=>$var){
			$this->$key=is_array($this->$key)?array_merge($this->$key,$var):$var;
		}
		$this->gerText();
		$this->aes=$this->yum->vars('app','encryption');
	}
	private function gerText(){
		$this->texto=$this->gerString();
		return $this->texto;
	}
	public function showImage(){
		$this->coding();
		$this->gerImage();
		header("Content-type: image/png");
		ImagePng($this->im);
	}
	private function gerImage(){
		$this->w=($this->numChars*$this->charx)+15;
		$this->im = imagecreatetruecolor($this->w,$this->h);
		imagefill($this->im,0,0,$this->getColor($this->colBorder));
		imagefilledrectangle ($this->im,1,1,($this->w-2),($this->h-2),$this->getColor($this->colBG));
		for ($i=1;$i<=$this->numCirculos;$i++){
			$randomcolor = imagecolorallocate($this->im,rand(100,255),rand(100,255),rand(100,255));
			imageellipse($this->im,rand(0,$this->w-10),rand(0,$this->h-3),rand(20,60),rand(20,60),$randomcolor);
		}
		$ident=5;
		for($i=0;$i<$this->numChars;$i++){
			$char=substr($this->texto,$i,1);
			$font=rand(4,5);
			$y=round(($this->h-15)/2);
			$col=$this->getColor($this->colTxt);
			if(rand(0,8)>=2){
				imagechar($this->im,$font,$ident,$y,$char,$col);
			}else{
				imagecharup($this->im,$font,$ident,$y+10,$char,$col);
			}
			$ident=$ident+$this->charx;
		}
	}
	private function getColor($var){
		$rgb = explode(" ",$var);
		$col = imagecolorallocate($this->im, $rgb[0], $rgb[1], $rgb[2]);
		return $col;
	}
	private function gerString(){
		$possible="aAGbNHaceCfdhLMjkrStDVxY124579";
		$str="";
		$len=strlen($possible);
		for($i=0;$i<$this->numChars;$i++){
			$str.=substr($possible,(rand()%$len),1);
		}
		$txt=$str;
		return $txt;
	}
	private function coding(){
		$encrypt=$this->yum->library('encrypt');
    	$code= $encrypt->stringToHex($this->texto."|".$this->yum->runtime);
		$code=$encrypt->encrypt($code,$this->aes);
		$this->yum->cookie('captcha',$code);
	}
	public function check($word,$time=false){
		$cvad=$this->yum->cookie('captcha');
		if(isset($cvad)){
			$encrypt=$this->yum->library('encrypt');
			$cvad=$encrypt->decrypt($cvad,$this->aes);
			$cvad=$encrypt->hexToString($cvad);
			$cvad=explode('|',$cvad);
			if($time!==false){
				if(($time+intval($cvad[1]))<$this->yum->runtime){
					return false;
				}
			}
			if((strcasecmp($cvad[0],$word)===0)){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
}
?>